<?php
/**
 * Created by PhpStorm.
 * User: summercode
 * Date: 2018/12/26
 * Time: 10:57 AM
 */

namespace app\index\controller;


use app\common\controller\BaseModel;
use app\common\model\DeviceModel;
use app\common\model\OrderModel;
use app\common\model\PhoneModel;
use app\common\model\SellerInfoModel;
use app\common\model\SellerModel;
use app\common\model\TicketCheckModel;
use app\common\model\TicketModel;
use app\common\model\UserModel;
use think\Request;

class Seller extends BaseModel
{
    // 构造方法
    public function  __construct(Request $request = null)
    {
        header('Access-Control-Allow-Origin: *');
        parent::__construct($request);
    }


    /**
     * 注册经销商用户
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sgin(Request $request) {

        $data = [
           'uname' => $request->param('phone'),
           'yz' => $request->param('yz'),
           'password' => $request->param('password'),
        ];

        $phone = new PhoneModel();
        $seller = new SellerModel();
        $res = $phone->where('phone' , $data['uname'])->find();

        if ($res['sms'] == $data['yz']) {
            if ((time() - $res['update_time']) > 300) {
                return $this->json_data(1, '000007', '验证码已过期', '', '');
            }

            $res2 = $seller->where('uname', $data['uname'])->find();
            if ($res2) {
                return $this->json_data(1, '000006', '该手机号已注册', '', '');
            } else {
                $seller->data([
                    'uname' => $data['uname'],
                    'password' => $data['password'],
                ])->save();
                return $this->json_data(0, '000000', '注册成功', '', '');
            }

        } else {
            return $this->json_data(1, '000005', '验证码错误请重新注册', '', '');
        }
    }


    /**
     *
     * 注册验证码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendSms(Request $request) {
        $phone = $request->param('phone');

        $sellerInfo = new SellerInfoModel();
        $seller = new SellerModel();

        $res = $sellerInfo->whereOr('phone1', $phone)->whereOr('phone2', $phone)->find();



        if ($res) {

            $res2 = $seller->where('uname', $phone)->find();

            if ($res2) {
                return $this->json_data(1, '200002', '该手机号已经注册过账号', '', '');
            }
            $this->smsToPhone($phone);
            return $this->json_data(1, '000000', '验证码已发请注意查收', '', '');

        } else {
            return $this->json_data(1, '200001', '该手机号不是经销商，如有问题请联系总部', '', '');
        }
    }


    /**
     * 短信登录验证码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendSms2(Request $request) {
        $phone = $request->param('phone');

        $sellerInfo = new SellerInfoModel();
        $seller = new SellerModel();

        $res = $sellerInfo->whereOr('phone1', $phone)->whereOr('phone2', $phone)->find();

        $seller_data = $seller->where('uname', $phone)->find();

        if (!$seller_data) {
            return $this->json_data(0, '200002', '用户请先注册后才能短信登录', '', '');
        }



        if ($res) {
            $data = $this->smsToPhone($phone);

            if ($data == '160040') {
                return $this->json_data(0, '160040', '今日验证码发送已达上限', '', '');
            }
//          $data = json_decode($data,true);

            return $this->json_data(1, '000000', '验证码已发请注意查收', $data, '');
        } else {
            return $this->json_data(0, '200001', '该手机号不是经销商，如有问题请联系总部', '', '');
        }
    }


    /**
     *
     * 账号密码登录
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function login(Request $request) {

        $data = [
            'uname' => $request->param('uname'),
            'password' => $request->param('password')
        ];

        if (empty($data['uname']) || empty($data['password'])) {
            return $this->json_data(1, '300001', '请输入账号或密码', '', '');
        }

        $seller = new SellerModel();

        $res = $seller->where('uname', $data['uname'])->value('password');

        if ($res == $data['password']) {

            $user = $seller->where('uname', $data['uname'])->find();
            return $this->json_data(1, '000000', '登录成功', $user['id'], '');
        } else {
            return $this->json_data(0, '100001', '密码错误', '', '');
        }

    }


    /**
     *
     *  短信登录
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function smsLogin(Request $request) {

        $data = [
            'uname' => $request->param('uname'),
            'sms' => $request->param('sms')
        ];

        if (empty($data['uname']) || empty($data['sms'])) {
            return $this->json_data(1, '300001', '请输入手机或者验证码', '', '');
        }

        $phoneModel = new PhoneModel();
        $seller = new SellerModel();

        $res = $phoneModel->where('phone', $data['uname'])->value('sms');

        if ($res == $data['sms']) {
            $user = $seller->where('uname', $data['uname'])->find();
            return $this->json_data(1, '000000', '登录成功', $user['id'], '');
        } else {
            return $this->json_data(0, '100001', '密码错误', '', '');
        }

    }

    /**
     * 判断券是否合法
     * @param Request $request
     * @return \think\response\Json
     */

    public function isTicket(Request $request) {
        $qid = $request->param('qid');

        $ticketModel = new TicketModel();
        $res = $ticketModel->where('id', $qid)->value('is_check');
        $validate = $ticketModel->where('id', $qid)->value('validate');

        if ($res == 1) {
            return $this->json_data(0, '500001', '券已核销', '', '');
        }

        if ($validate < time()) {
            return $this->json_data(0, '500002', '活动已过期', '', '');
        }

        return $this->json_data(0, '000000', '合法的券ID', '', '');
    }


    public function deviceList() {

        $deviceModel = new DeviceModel();

        $data = $deviceModel->select();

        return $this->json_data(0, '000000', 'device 列表', $data, '');

    }

    /**
     *
     *  核销券方法
     * @param Request $request
     * @return \think\response\Json
     *
     *      1、在核销记录表中添加一条记录
     *      2、在抵价券表中修改抵价券的状态
     *  todo 20181227    3、在用户表中添加一次抽奖次数   ok
     *
     */
    public function checkTicket(Request $request) {
        $data = [
            'uid' => $request->param('uid'),
            'oid' => $request->param('oid'),
            'qid' => $request->param('qid'),
            'sid' => $request->param('sid'),
            'goods' => $request->param('goods'),
            'code' => $request->param('code')
        ];

        // 核销记录模型
        $ticketCheck = new TicketCheckModel();

        // 抵价券模型
        $ticket = new TicketModel();

        // 用户模型
        $user = new UserModel();

        $ticket->where('id', $data['qid'])->update([
            'is_check' => 1
        ]);

        $count = $user->where('id', $data['uid'])->value('count');

        $user->where('id', $data['uid'])->update([
            'count' => ++$count
        ]);

        $ticketCheck->data($data)->save();

        return  $this->json_data(0, '000000', '核销成功', $data, '');

    }


    public function getTicketInfo(Request $request) {
        $qid = $request->param('qid');

        $ticket = new TicketModel();

        return  $this->json_data(0, '000000', '券信息', $ticket->where('id', $qid)->find(), '');

    }

    public function getMyCheckData(Request $request) {

        $sid = $request->param('sid');
        $page = $request->param('page') ? $request->param('page') : 1;
        $num = $request->param('num') ? $request->param('num') : 5;

        $ticketCheck = new TicketCheckModel();
        $order = new OrderModel();
        $user = new UserModel();
        $ticket = new TicketModel();

        $data = $ticketCheck->where('sid', $sid)
            ->limit(($page - 1) * $num, $num)
            ->order('update_time', 'desc')
            ->select();

        $result = array();

        foreach ($data as $item) {
            $userData = $user->where('id', $item['uid'])->find();
            $orderData = $order->where('id', $item['oid'])->find();
            $ticketData = $ticket->where('id', $item['qid'])->find();

            $item['user'] = $userData;
            $item['order'] = $orderData;
            $item['ticket'] = $ticketData;
            $item['update_time'] = date("Y-m-d H:i:s", $item['update_time']);
            $item['create_time'] = date("Y-m-d H:i:s", $item['create_time']);

            array_push($result, $item);
        }


        return  $this->json_data(0, '000000', '券信息', [
            'total' => count($ticketCheck->where('sid', $sid)->select()),
            'data' => $result
        ], '');

    }



}